package com.myclass.dynamicdatasource.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * Desc: 数据源路由，观察当前数据源
 *
 * @author wujw
 * @email jiwenwu@outlook.com
 * @date 2018-12-12
 */
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
    private Logger logger = LoggerFactory.getLogger(DynamicRoutingDataSource.class);

    @Override
    protected Object determineCurrentLookupKey() {
        logger.info("当前数据源为 >>>>>>>>>[ {} ]",DynamicDataSourceContextHolder.getDataSourceKey());

        String key = DynamicDataSourceContextHolder.getDataSourceKey();
        // 最怕首次使用的为写方法，所以直接放入两个主库吧
        if (key == null){
            DynamicDataSourceContextHolder.setDataSourceKey(DataSourceKey.type_one_master.name());
            DynamicDataSourceContextHolder.setDataSourceKey(DataSourceKey.type_two_master.name());
        }
        return DynamicDataSourceContextHolder.getDataSourceKey();
    }
}
